<?php
/**
 * Created by PhpStorm.
 * Author: yostar
 * User: THINK
 * Date: 2018/5/31
 * Time: 16:29
 */

namespace wechat\model;

use wechat\model\Common as WeChat;

require_once 'Common.php';

class AutoReply extends WeChat
{
    public $token = ''; // 设置的token
    public $debug = ''; // 是否记录调试日志
    public $flag = false; // FuncFlag
    public $msgType = 'text';
    public $msg = []; // 用户发送的信息

    public function __construct($token = '', $debug = false)
    {
        $this->token = $token;
        $this->debug = $debug;
    }

    /**
     * 获取用户发送的信息并转换成数组
     */
    public function getMessage()
    {
        $postStr = file_get_contents("php://input");
//        $postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
        if (!empty($postStr)) {
            $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->msgType = strtolower($this->msg['MsgType']);
        }
    }

    /**
     * @param string $text 发送的文本消息内容
     * @return string
     */
    public function textMessage($text)
    {
        $createTime = time();
        $textTpl = "<xml>
                        <ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
                        <FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
                        <CreateTime>{$createTime}</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
        return sprintf($textTpl, $text);


    }

    /**
     * @param string $msgType 消息类型 默认为回复图片信息
     * @param string $mediaID 通过素材管理中的接口上传多媒体文件，得到的id。
     * @return string
     */
    public function mediaMessage($mediaID, $msgType = 'image')
    {
        $createTime = time();
        $mediaTpl = "<xml><ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName><FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName><CreateTime>{$createTime}</CreateTime><MsgType><![CDATA[%s]]></MsgType><Image><MediaId><![CDATA[%s]]></MediaId></Image></xml>";
        $this->log('format: ' . sprintf($mediaTpl, $msgType, $mediaID));
        return sprintf($mediaTpl, $msgType, $mediaID);
    }

    /**
     * @param string $videoID 通过素材管理中的接口上传多媒体文件，得到的id。
     * @param string $title 视频标题
     * @param string $description 视频描述
     * @return string
     */
    public function videoMessage($videoID, $title = '', $description = '')
    {
        $createTime = time();
        $videoTpl = "<xml><ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName><FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName><CreateTime>{$createTime}</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[%s]]></MediaId><Title><![CDATA[{$title}]]></Title><Description><![CDATA[{$description}]]></Description></Video>
                        </xml>";
        $this->log("format: " . sprintf($videoTpl, $videoID));
        return sprintf($videoTpl, $videoID);
    }

    /**
     * @param string $thumbMediaId 缩略图的媒体id，通过素材管理中的接口上传多媒体文件，得到的id
     * @param string $title 音乐标题
     * @param string $description 音乐描述
     * @param string $musicUrl 音乐链接
     * @param string $HQMusicUrl 高质量音乐链接，WIFI环境优先使用该链接播放音乐
     * @return string
     */
    public function musicMessage($thumbMediaId, $title, $description, $musicUrl, $HQMusicUrl)
    {
        $createTime = time();
        $musicTpl = "<xml><ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName><FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName><CreateTime>{$createTime}</CreateTime><MsgType><![CDATA[music]]></MsgType><Music><Title><![CDATA[{$title}]]></Title><Description><![CDATA[{$description}]]></Description><MusicUrl><![CDATA[{$musicUrl}]]></MusicUrl><HQMusicUrl><![CDATA[{$HQMusicUrl}]]></HQMusicUrl><ThumbMediaId><![CDATA[{$thumbMediaId}]]></ThumbMediaId></Music></xml>";
        $this->log("format: " . $musicTpl);
        return $musicTpl;

    }

    /**
     * @param array $newsData include ['title', 'description', 'picUrl', 'url']
     * @return string
     */
    public function articleMessage($newsData = [])
    {
        $createTime = time();
        $musicTplHeader = "<xml><ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName><FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName><CreateTime>{$createTime}</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>%u</ArticleCount><Articles>";
        $musicTplItem = "<item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item>";
        $musicTplFooter = '</Articles></xml>';
        // 图文消息最多八条
        $articleCount = count($newsData) > 8 ? 8 : count($newsData);
        $articles = sprintf($musicTplHeader, $articleCount);
        if ($articleCount) {
            foreach ($newsData as $key => $item) {
                $articles .= sprintf($musicTplItem, $item['title'], $item['description'], $item['picUrl'], $item['url']);
            }
        }
        $articles .= $musicTplFooter;
        return $articles;
    }

    /**
     * token验证入口
     */
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    /**
     * 执行token验证
     * @return bool
     */
    public function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }
}